import axios from "axios";
import {logbackCreate} from "@/api";
import segmentation from "../../public/configuration";
import {upload} from "@/api/index1";
//succeed 是否成功
let dailyRecord = (succeed,name,modeling) => {
   console.log((succeed))

    axios.get('/api/testpage/get_ip').then((res)=>{

        let data = {
            appKey:'Adversarial Examples on Images',
            operateTime:getCurrentDateTime(),
            operateIp: res.ip,
            authUserId:sessionStorage.getItem('id')
        }
        logbackCreate(data)
        console.log(JSON.parse((JSON.parse(sessionStorage.getItem(name))[JSON.parse(sessionStorage.getItem(name)).length-1])))
     if (sessionStorage.getItem(name) && JSON.parse((JSON.parse(sessionStorage.getItem(name))[JSON.parse(sessionStorage.getItem(name)).length-1])).gen_path) {

            axios.post('/api/wbt/get_images', {
                img_dir: JSON.parse((JSON.parse(sessionStorage.getItem(name))[JSON.parse(sessionStorage.getItem(name)).length-1])).gen_path
            }).then((res) => {
                console.log( res)
                res.data.image.forEach(item => {
                    convertToFile(item, name, modeling)
                })
            })
        }
    })

}

function getCurrentDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1; // 月份是从0开始的，所以需要+1
    var day = now.getDate();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();

    // 补零操作，确保月、日、时、分、秒都是两位数
    month = (month < 10 ? "0" : "") + month;
    day = (day < 10 ? "0" : "") + day;
    hours = (hours < 10 ? "0" : "") + hours;
    minutes = (minutes < 10 ? "0" : "") + minutes;
    seconds = (seconds < 10 ? "0" : "") + seconds;

    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}
// const convertToFile = (val,name,modeling) =>{
//     let file = []
//     val.forEach(item=>{
//         file.push(convertToFileList(item,name,modeling))
//     })
//     uploadingFun(file,val,name,modeling)
// }
async function convertToFile (val,name,modeling) {
    let paths = JSON.parse((JSON.stringify(val)))
    if(paths){
        const url = paths.replace(paths.split(segmentation.segmentation)[0], 'images/' + segmentation.segmentation)
        try {
            const response = await fetch(url);
            const blob = await response.blob();
            const file = new File([blob], "image.jpg", { type: "image/jpeg" });
            uploadingFun(file,val,name,modeling)
        } catch (error) {
            console.error("转换失败:", error);
        }
    }

}
function uploadingFun(image,path,name,modeling) {
    let formData = new FormData();
    formData.append('file',image)
    upload(formData).then((res=>{
        if(res.code == 200){
           setTimeout(()=>{
               ResultSynchronization(path,res,name,modeling)
           })
        }
    }))
}
let keyList = {
    eps: 'eps',
    model: '模型',
    dataset: '数据集',
    out_path: '输出路径',
    gen_path: '生成路径',
    deepfool_overshoot: '扰动超出决策边界程度',
    deepfool_steps: '步长',
    cw_kappa:'置信度',
    cw_lr: '学习率',
    cw_steps: '步长',
    cw_c: '扰动强度权重',
    pgd_eps:'pgd_eps',
    pgd_alpha: '扰动迭代步长',
    pgd_steps: '步长',
    sim_target: '是否有目标攻击',
    sim_attack_mode: '攻击模式',
    sim_maxlter: '最大迭代次数',
    sim_eps: 'sim_eps',
    sim_iter_whole_dataset: '是否遍历整个数据集',
    sim_attack_sample_number: '攻击样本数量',
    ba_targeted: '是否有目标攻击',
    ba_max_iter: '最大迭代次数',
    ba_iter_whole_dataset:'是否遍历整个数据集',
    ba_attack_sample_number: '攻击样本数量',
}
function ResultSynchronization(val,res,name,modeling) {
    let inputParams = [

    ]
    for(let i in Object.keys(modeling)){
        inputParams.push(
            {
                "label": Object.keys(modeling)[i],
                "key": keyList[Object.keys(modeling)[i]],
                "value": modeling[Object.keys(modeling)[i]]
            }
        )
    }
    // let EnglishName = val.imge_real.path.split('/')[val.imge_real.path.split('/').length - 1]
    let data = JSON.stringify({
        "methodType": "DATA_DETECTION",
        "methodName": "自动驾驶数据集对抗样本检测算法",
        "infos": [
            {
                "label": "业务场景",
                "value": "",
            },
            {
                "label": "检测对象",
                "value": "自动驾驶数据",
            },
            {
                "label": "风险类型",
                "value": "",
            },
            {
                "label": "针对模型",
                "value": modeling.model,   //即form表单中用户选择的 <模型> 的值
            },
            {
                "label": "攻击算法",
                "value": name, //即调用的具体算法的名称
            }
        ],
        "inputFiles": [

        ],
        "inputParams": inputParams,
        "outputFiles": [
            {
                "originalName":  res.data.originalName,
                "url": res.data.url,
                "fileType": "IMAGE"
            }
        ],
        "outputParams": [

        ]
    })

    var xhr = new XMLHttpRequest();
    xhr.open('POST', segmentation.SynchronizationResult + '/api/send/result/info', true);
    xhr.setRequestHeader('Content-Type', 'application/json')
    // 设置请求头参数
    xhr.setRequestHeader('appKey', 'nsfocus-aeoi-det');
    xhr.setRequestHeader('appSecret', 'bnNmb2N1cy1hZW9pLWRldC1ibk5tYjJOMWN5MWhaVzlwTFdSbGRBPT0=');
// 发送数据
    xhr.send(data);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 请求成功
            console.log(xhr.responseText);
        } else {
            // 请求失败
            console.error(xhr.statusText);
        }
    };
}

export default {
    dailyRecord,
    convertToFile
}



